#!/usr/bin/env python3
# coding:utf-8
import time
import paho.mqtt.client as mqtt


class MqttPublisher:
    def __init__(self, broker_address, port=1883):
        self.broker_address = broker_address
        self.port = port
        # self.mqtt = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
        self.mqtt = mqtt.Client()
        self.mqtt.on_publish = self.on_publish

    # def on_publish(self, client, userdata, mid, reason_code, properties):
    def on_publish(self, client, userdata, mid):
        try:
            print("send mqtt msg")
        except KeyError:
            print("on_publish error")

    def start(self):
        self.mqtt.connect(self.broker_address, self.port)
        # self.mqtt.loop_start()

    def stop(self):
        self.mqtt.disconnect()
        self.mqtt.loop_stop()

    def loop_test(self):
        count = 0
        while True:
            self.mqtt.publish("font", f"count={count}")
            time.sleep(0.1)
            print("mqtt pushlish count=", count)
            count += 1

    def input_cmd_test(self):
        help_str = """
    w 前进
a 向左      s 向右
    s 向后

"""
        topic_name = ""
        topic_buf = ""
        while True:
            topic_name = ""
            cmd = input(help_str)
            if cmd == "w":
                topic_name = "font"
                topic_buf = "x=1.0"
            elif cmd == "s":
                topic_name = "back"
                topic_buf = "x=-1.0"
            elif cmd == "a":
                topic_name = "left"
                topic_buf = "z=0.5"
            elif cmd == "d":
                topic_name = "right"
                topic_buf = "z=-0.5"
            elif cmd == "q":
                break
            else:
                print("未知命令")
                print(help_str)
            if topic_name != "":
                print(f"send mqtt msg {topic_name}: {topic_buf}")
                msg = self.mqtt.publish(topic_name, topic_buf, qos=1)
                # msg.wait_for_publish()


# 使用示例
if __name__ == '__main__':
    pub = MqttPublisher('127.0.0.1')
    pub.start()
    # pub.loop_test()
    pub.input_cmd_test()

    # 保持主程序运行，直到手动停止
    try:
        while True:
            pass
    except KeyboardInterrupt:
        pub.stop()
